package com.ibeeking.found.msg.rest.service.impl;

import com.ibeeking.found.common.config.prop.FileOssProp;
import com.ibeeking.found.common.enums.PublishStatusEnum;
import com.ibeeking.found.msg.rest.service.IWxMpAutoMessageService;
import com.ibeeking.found.msg.rest.service.IWxMpSourceService;
import com.ibeeking.found.msg.rest.service.IWxMpAutoMessageKeyService;
import com.ibeeking.found.msg.service.common.bo.WxMpAutoMessageBO;
import com.ibeeking.found.msg.service.common.dos.WxMpAutoMessageDO;
import com.ibeeking.found.msg.service.common.param.WxMpAutoMessageParam;
import com.ibeeking.found.msg.service.common.query.WxMpAutoMessagePageQuery;
import com.ibeeking.found.msg.service.common.query.WxMpAutoMessageQuery;
import com.ibeeking.found.msg.service.common.vo.WxMpSourceVO;
import com.ibeeking.found.msg.service.common.vo.WxMpAutoMessageKeyVO;
import com.ibeeking.found.msg.service.common.vo.WxMpAutoMessageVO;
import com.ibeeking.found.msg.service.mapper.WxMpAutoMessageMapper;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.json.JsonUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName WxMpAutoMessageServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-02-05 19:11
 **/
@Deprecated
@Service
public class WxMpAutoMessageServiceImpl extends ServiceImpl<WxMpAutoMessageMapper, WxMpAutoMessageDO> implements IWxMpAutoMessageService {

    @Resource
    private WxMpAutoMessageMapper wxmpAutoMessageMapper;

    @Resource
    private IWxMpAutoMessageKeyService wxmpAutoMessageKeyService;

    @Resource
    private IWxMpSourceService mpSourceService;

    @Resource
    private FileOssProp fileOssProp;


    @Override
    public List<WxMpAutoMessageVO> list(WxMpAutoMessageQuery query) {
        List<WxMpAutoMessageDO> wxMpAutoMessageDOS = wxmpAutoMessageMapper.selectList(new LambdaQueryWrapper<WxMpAutoMessageDO>());
        return JsonUtils.jsonToList(wxMpAutoMessageDOS, WxMpAutoMessageVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Page<WxMpAutoMessageVO> pageList(WxMpAutoMessagePageQuery pageQuery, int index) {
        Page<WxMpAutoMessageDO> pages = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        QueryWrapper<WxMpAutoMessageDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WxMpAutoMessageDO::getEventType, pageQuery.getEventType())
                .eq(WxMpAutoMessageDO::getEventType, pageQuery.getEventType())
                .like(StringUtils.isNotBlank(pageQuery.getRuleName()), WxMpAutoMessageDO::getRuleName, pageQuery.getRuleName());
        pages = wxmpAutoMessageMapper.selectPage(pages, queryWrapper);
        if (index == 0) {
            if ((!"key".equals(pageQuery.getEventType())) && pages.getRecords().size() == 0) {
                WxMpAutoMessageParam param = new WxMpAutoMessageParam();
                param.setEventType(pageQuery.getEventType());
                param.setAppId(pageQuery.getAppId());
                WxMpAutoMessageParam.Message message = new WxMpAutoMessageParam.Message();
                message.setSourceType("TEXT");
                message.setUnionKey(" ");
                param.setMessage(message);
                this.add(param);
                index = 1;
                return this.pageList(pageQuery, index);
            }
        }
        Page<WxMpAutoMessageVO> voPage = new Page<>();
        voPage.setTotal(pages.getTotal());
        voPage.setRecords(pages.getRecords().stream().map(node -> {
            WxMpAutoMessageVO vo = new WxMpAutoMessageVO();
            BeanUtils.copyProperties(node, vo);
            WxMpAutoMessageVO.Message message = new WxMpAutoMessageVO.Message();
            message.setUnionKey(node.getUnionKey());
            message.setSourceType(node.getSourceType());
            vo.setMessage(message);
            return vo;
        }).collect(Collectors.toList()));
        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(WxMpAutoMessageParam param) {
        WxMpAutoMessageDO wxmpAutoMessageDO = BeanUtil.convertBean(param, WxMpAutoMessageDO.class);
        wxmpAutoMessageDO.setUnionKey(param.getMessage().getUnionKey());
        wxmpAutoMessageDO.setSourceType(param.getMessage().getSourceType());
        wxmpAutoMessageDO.setCreateTime(LocalDateTime.now());
        wxmpAutoMessageDO.setModifyTime(LocalDateTime.now());
        boolean flag = wxmpAutoMessageMapper.insert(wxmpAutoMessageDO) > 0;
        if (flag && "key".equals(param.getEventType())) {
            List<String> keys = param.getKeys();
            if (this.wxmpAutoMessageKeyService.add(wxmpAutoMessageDO, keys)) {
                flag = true;
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                flag = false;
            }
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean modify(WxMpAutoMessageParam param) {
        WxMpAutoMessageDO wxmpAutoMessageDO = BeanUtil.convertBean(param, WxMpAutoMessageDO.class);
        wxmpAutoMessageDO.setUnionKey(param.getMessage().getUnionKey());
        wxmpAutoMessageDO.setSourceType(param.getMessage().getSourceType());
        wxmpAutoMessageDO.setModifyTime(LocalDateTime.now());
        boolean flag = wxmpAutoMessageMapper.updateById(wxmpAutoMessageDO) > 0;
        if (flag) {
            this.wxmpAutoMessageKeyService.delByMessageId(wxmpAutoMessageDO.getId());
            List<String> keys = param.getKeys();
            if (this.wxmpAutoMessageKeyService.add(wxmpAutoMessageDO, keys)) {
                flag = true;
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                flag = false;
            }
        }
        return flag;
    }

    @Override
    public WxMpAutoMessageVO view(Long id) {
        WxMpAutoMessageDO wxmpAutoMessageDO = wxmpAutoMessageMapper.selectById(id);
        WxMpAutoMessageVO vo = BeanUtil.convertBean(wxmpAutoMessageDO, WxMpAutoMessageVO.class);
        WxMpAutoMessageVO.Message message = new WxMpAutoMessageVO.Message();
        message.setSourceType(wxmpAutoMessageDO.getSourceType());
        message.setUnionKey(wxmpAutoMessageDO.getUnionKey());
        message.setAppId(wxmpAutoMessageDO.getAppId());
        if (!"TEXT".equals(wxmpAutoMessageDO.getSourceType())) {
            WxMpSourceVO sourceVO = this.mpSourceService.view(Long.valueOf(wxmpAutoMessageDO.getUnionKey()));
            if (sourceVO != null) {
                if ("IMAGE_TEXT".equals(wxmpAutoMessageDO.getSourceType())) {
                    if (sourceVO != null) {
                        message.setMpSourceNewsPageVos(sourceVO.getSourceDetail());
                    } else {
                        message.setMpSourceNewsPageVos(new ArrayList());
                    }
                } else {
                    message.setRepName(sourceVO.getName());
                    if (StringUtils.isNotBlank(sourceVO.getPath())) {
                        message.setRepUrl(fileOssProp.getHost() + sourceVO.getPath());
                    } else {
                        message.setRepUrl("");
                    }
                }
            }
        }
        if ("key".equals(wxmpAutoMessageDO.getEventType())) {
            List<WxMpAutoMessageKeyVO> keys = this.wxmpAutoMessageKeyService.queryListByMessageId(id);
            List<String> ids = keys.stream().map(key -> key.getKeyWord()).collect(Collectors.toList());
            vo.setKeys(ids);
        }
        vo.setMessage(message);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean changeStatus(Long id, Integer status) {
        WxMpAutoMessageDO wxmpAutoMessageDO = new WxMpAutoMessageDO();
        wxmpAutoMessageDO.setId(id);
        wxmpAutoMessageDO.setPublishStatus(status);
        wxmpAutoMessageDO.setModifyTime(LocalDateTime.now());
        return wxmpAutoMessageMapper.updateById(wxmpAutoMessageDO) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean del(Long id) {
        WxMpAutoMessageDO wxmpAutoMessageDO = this.wxmpAutoMessageMapper.selectById(id);
        if (wxmpAutoMessageDO == null) {
            return true;
        }
        PublishStatusEnum.statusCheckException(wxmpAutoMessageDO.getPublishStatus());
        if (this.wxmpAutoMessageKeyService.delByMessageId(id)) {
            return wxmpAutoMessageMapper.deleteById(id) > 0;
        }
        return false;
    }

    @Deprecated
    @Override
    public List<WxMpAutoMessageBO> queryByCondition(WxMpAutoMessageDO messageDO) {
        wxmpAutoMessageMapper.selectList(new LambdaQueryWrapper<>(WxMpAutoMessageDO.class)
                .eq(WxMpAutoMessageDO::getPublishStatus, PublishStatusEnum.ENABLE.getValue())
                .eq(WxMpAutoMessageDO::getAppId, messageDO.getAppId())
                .eq(WxMpAutoMessageDO::getEventType, messageDO.getEventType())
                .eq(WxMpAutoMessageDO::getSourceType, messageDO.getSourceType())
        );
        return null;
    }


}
